package SQL;

import java.sql.*;
import java.util.Vector;

public class Connections {
    private Connection con;
    private Statement stm;
    private ResultSet rs;

    public Connections() {
    }

    public Connection getConnection(){

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //数据库名称：ticketsystem
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3307/ticketsystem?serverTimezone=UTC",
                    "root", "root1234");

            System.out.println("数据库连接成功");


            //返回连接的成果
            return con;

        } catch(ClassNotFoundException ex){
            ex.printStackTrace();
            System.out.println("数据库驱动程序找不到!");

        }catch(SQLException ex){
            ex.printStackTrace();
            System.out.println("数据库连接失败!");

        }

        return null;
    }


    //将数据库中的查询结果保存在Vector中的方法
    public static Vector<Vector> queryData(String sql){
        try{
            //创建会话对象
            Connections connections = new Connections();
            Connection con = connections.getConnection();
            Statement stm = con.createStatement();
            //执行查询,返回结果集
            ResultSet rs = stm.executeQuery(sql);
            //二维的Vector
            Vector<Vector> data = new Vector<Vector>();
            //获取结果集的元素据
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取结果集的字段个数
            int count = rsmd.getColumnCount();

            while (rs.next()){
                //定义保存一行数据的Vector
                Vector line = new Vector();
                for(int i = 1;i<=count;i++){
                    line.add(rs.getObject(i));
                }
                data.add(line);
            }
            return data;
        }catch (SQLException e){
            System.out.println("数据库访问异常");
            e.printStackTrace();
            return null;
        }
    }

}
